package com.gengzp.mq.client.core.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.gengzp.mq.client.core.MqCoreFunc;
import com.gengzp.mq.client.enums.MqMessageStatusEnum;
import com.gengzp.mq.client.model.generic.MqPaginationResult;
import com.gengzp.mq.client.model.generic.MqResult;
import com.gengzp.mq.client.model.message.MqMessage;
import com.gengzp.mq.client.model.message.MqPageMessageResp;
import com.gengzp.mq.client.model.topic.MqTopicResp;
import com.gengzp.mq.client.tools.MqEnvironmentVariableReader;
import com.gengzp.mq.client.tools.MqHttpRequester;
import com.gengzp.mq.client.tools.MqJsonConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.gengzp.mq.client.constants.MqRequestCodeConstants.SUCCESS;
import static com.gengzp.mq.client.constants.MqRequestUrlConstants.*;

/**
 * @ClassName MqCoreFuncImpl
 * @Description
 * @Author gengzp
 * @Date 2025/9/4 17:57
 */
@Component
public class MqCoreFuncImpl implements MqCoreFunc {

    private static final Logger logger = LoggerFactory.getLogger(MqCoreFuncImpl.class);

    @Autowired
    private MqEnvironmentVariableReader mqEnvironmentVariableReader;

    @Override
    public void createTopic(String topicName, String description) {
        if (topicName == null || topicName.isBlank()) {
            logger.error("主题 topic 创建失败, 主题名称不能为空");
            throw new RuntimeException("主题名称 topicName 不能为空");
        }
        if (description == null || description.isBlank()) {
            logger.error("主题 topic 创建失败, 主题描述不能为空");
            throw new RuntimeException("主题描述 description 不能为空");
        }

        MqResult<String> createTopicResult = MqHttpRequester.post(
                mqEnvironmentVariableReader.getMqAddress() + CREATE_TOPIC,
                Map.of("topic", topicName, "topicDescription", description),
                new HashMap<>(),
                new TypeReference<>() {
                }
        );
        if (SUCCESS != createTopicResult.getCode()) {
            logger.error("创建 topic 失败, " + createTopicResult.getMessage());
            throw new RuntimeException("创建 topic 失败, " + createTopicResult.getMessage());
        }

        logger.info("创建 topic 成功, 主题名称: " + topicName);
    }

    @Override
    public void editTopicDescription(String topicName, String description) {
        if (topicName == null || topicName.isBlank()) {
            logger.error("主题描述编辑失败, 主题名称不能为空");
            throw new RuntimeException("主题名称 topicName 不能为空");
        }
        if (description == null || description.isBlank()) {
            logger.error("主题描述编辑失败, 主题描述不能为空");
            throw new RuntimeException("主题描述 description 不能为空");
        }

        MqResult<String> createTopicResult = MqHttpRequester.post(
                mqEnvironmentVariableReader.getMqAddress() + EDIT_TOPIC_DESC,
                Map.of("topic", topicName, "topicDescription", description),
                new HashMap<>(),
                new TypeReference<>() {
                }
        );
        if (SUCCESS != createTopicResult.getCode()) {
            logger.error("主题描述编辑失败, " + createTopicResult.getMessage());
            throw new RuntimeException("主题描述编辑失败, " + createTopicResult.getMessage());
        }

        logger.info("主题描述编辑成功");
    }

    @Override
    public void removeTopic(String topicName) {
        if (topicName == null || topicName.isBlank()) {
            logger.error("主题删除失败, 主题名称 topicName 不能为空");
            throw new RuntimeException("主题名称 topicName 不能为空");
        }

        MqResult<String> createTopicResult = MqHttpRequester.post(
                mqEnvironmentVariableReader.getMqAddress() + REMOVE_TOPIC,
                Map.of("topic", topicName),
                new HashMap<>(),
                new TypeReference<>() {
                }
        );
        if (SUCCESS != createTopicResult.getCode()) {
            logger.error("主题删除失败, " + createTopicResult.getMessage());
            throw new RuntimeException("主题删除失败, " + createTopicResult.getMessage());
        }

        logger.info("主题删除成功");
    }

    @Override
    public List<MqTopicResp> searchAllTopic() {
        MqResult<List<MqTopicResp>> searchAllTopicResult = MqHttpRequester.post(
                mqEnvironmentVariableReader.getMqAddress() + LIST_TOPIC,
                null,
                new HashMap<>(),
                new TypeReference<>() {
                }
        );
        if (SUCCESS != searchAllTopicResult.getCode()) {
            logger.error("查询 topic 列表失败, " + searchAllTopicResult.getMessage());
            throw new RuntimeException("查询 topic 列表失败, " + searchAllTopicResult.getMessage());
        }

        return searchAllTopicResult.getData();
    }

    @Override
    public String sendMessage(String topic, String tag, String content) {
        if (topic == null || topic.isBlank()) {
            logger.error("发送消息失败, topic 不能为空");
            throw new RuntimeException("发送消息失败, topic 不能为空");
        }
        if (content == null || content.isBlank()) {
            logger.error("发送消息失败, content 不能为空");
            throw new RuntimeException("发送消息失败, content 不能为空");
        }

        MqResult<String> sendMessageResult = MqHttpRequester.post(
                mqEnvironmentVariableReader.getMqAddress() + SEND_MESSAGE,
                Map.of("topic", topic, "tag", tag, "content", content),
                new HashMap<>(),
                new TypeReference<>() {
                }
        );
        if (SUCCESS != sendMessageResult.getCode()) {
            logger.error("发送消息失败, " + sendMessageResult.getMessage());
            throw new RuntimeException("发送消息失败, " + sendMessageResult.getMessage());
        }

        logger.info("发送消息成功, 消息id: " + sendMessageResult.getData());
        return sendMessageResult.getData();
    }

    @Override
    public void resendMessage(String messageId) {
        if (messageId == null || messageId.isBlank()) {
            logger.error("重发消息失败, messageId 不能为空");
            throw new RuntimeException("重发消息失败, messageId 不能为空");
        }

        MqResult<String> resendMessageResult = MqHttpRequester.post(
                mqEnvironmentVariableReader.getMqAddress() + RESEND_MESSAGE,
                Map.of("messageId", messageId),
                new HashMap<>(),
                new TypeReference<>() {
                }
        );

        if (SUCCESS != resendMessageResult.getCode()) {
            logger.error("消息重发失败, " + resendMessageResult.getMessage());
            throw new RuntimeException("消息重发失败, " + resendMessageResult.getMessage());
        }

        logger.info("发送消息成功, 消息id: " + resendMessageResult.getData());
    }

    @Override
    public MqMessage subscribe(String topic) throws Exception {
        MqResult<Map<String, String>> subscribeResult = MqHttpRequester.post(
                mqEnvironmentVariableReader.getMqAddress() + SUBSCRIBE_TOPIC,
                Map.of("topic", topic),
                new HashMap<>(),
                new TypeReference<>() {
                }
        );
        if (SUCCESS != subscribeResult.getCode()) {
            logger.info("订阅topic获取消息失败, " + subscribeResult.getMessage());
            throw new Exception("订阅topic获取消息失败, " + subscribeResult.getMessage());
        }
        if (subscribeResult.getData() == null) {
            return null;
        }
        return MqJsonConverter.convertJsonToObject(
                MqJsonConverter.convertObjectToJson(subscribeResult.getData()),
                MqMessage.class);
    }

    @Override
    public void ackMessage(String messageId) throws Exception {
        MqHttpRequester.post(
                mqEnvironmentVariableReader.getMqAddress() + ACK_MESSAGE,
                Map.of("messageId", messageId),
                new HashMap<>(),
                new TypeReference<>() {
                }
        );
    }

    @Override
    public MqPaginationResult<MqPageMessageResp> pageQueryMessage(int pageNum,
                                                                  int pageSize,
                                                                  String messageId,
                                                                  String topic,
                                                                  MqMessageStatusEnum messageStatusEnum) {
        if (topic == null || topic.isBlank()) {
            throw new RuntimeException("主题 topic 不能为空");
        }
        if (messageStatusEnum == null) {
            throw new RuntimeException("消息状态 messageStatusEnum 不能为空");
        }

        MqResult<MqPaginationResult<MqPageMessageResp>> result = MqHttpRequester.post(
                mqEnvironmentVariableReader.getMqAddress() + PAGE_QUERY_MESSAGE,
                Map.of("pageNum", pageNum,
                        "pageSize", pageSize,
                        "messageId", messageId,
                        "topic", topic,
                        "status", messageStatusEnum.getCode()),
                new HashMap<>(),
                new TypeReference<>() {
                }
        );
        if (SUCCESS != result.getCode()) {
            logger.info("分页查询消息失败, " + result.getMessage());
            throw new RuntimeException("分页查询消息失败, " + result.getMessage());
        }

        return result.getData();
    }

}
